package coop.bancocredicoop.proyectos.gd



import static org.springframework.http.HttpStatus.*
import coop.bancocredicoop.proyectos.gd.alfresco.Utils

import coop.bancocredicoop.proyectos.gd.Document;
import coop.bancocredicoop.proyectos.gd.DocumentType;
import grails.transaction.Transactional

@Transactional(readOnly = true)
class CorregirDocumentosController {

	def documentService
	
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

	def index(Document documentInstance) {
		def documentTypes = DocumentType.createCriteria().list {
			fileTypes {
				eq 'shortName', 'ALTA'
			}
			order 'versionable', 'desc'
			order 'name'
		}
		
		params.documentTypes = documentTypes
		
		if (!params.box)
			params.box = documentInstance.box.cajaId
		
		if (!params.customerId)
			params.customerId = documentInstance.customer.idPersona
		
		if (!params.customerDescription)
			params.customerDescription = "${documentInstance.customer.idPersona} (${documentInstance.customer.name}, CUIT: ${documentInstance.customer.cuit})"
		
		if (!params.documentType)
			params.documentType = documentInstance.documentType.id.toString()
		
		params.expirationDateAsDate = documentInstance.validTo

		if (!params.notes)
			params.notes = documentInstance.notes

		respond(documentInstance)
	}
	
	@Transactional
	def save() {
		def documentTypes = DocumentType.createCriteria().list {
			fileTypes {
				eq 'shortName', 'ALTA'
			}
			order 'versionable', 'desc'
			order 'name'
		}
		
		params.documentTypes = documentTypes
		params.expirationDateAsDate = params.date('expirationDate')

		def loggedInUser = session.usuario.userName		
		def document = Document.get(params.id)
		def now = new Date()
				
		/* validaciones */
		flash.errors = []
		
		if (!params.customerId)
			flash.errors += ['Debe ingresar un cliente.']

		if (!params.box)
			flash.errors += ['Debe ingresar una caja.']

		if (flash.errors) {
			render view: 'index'
			return
		}

		/* se anula el documento anterior */
		documentService.anular(document, loggedInUser)
		
		/* se da de alta un nuevo documento */
		
		def documentFile = request.getFile('inputDocument')
		
		if (documentFile.isEmpty()) {
			def byteArrayContent = new Utils(grailsApplication.config.alfresco).
					getClient(loggedInUser: loggedInUser).
					getContentAsByteArray(document)

			documentFile = [inputStream: new ByteArrayInputStream(byteArrayContent),
					originalFilename: 'x.pdf']
		}

		try {
			def result = documentService.createDocument(
					params.customerId,
					params.box,
					params.documentType,
					params.expirationDateAsDate,
					/* tags */ "",
					documentFile,
					loggedInUser,
					now,
					params.notes)
				
			flash.success = result.success
			if (result.success) {
				flash.message = "Documento guardado exitosamente."
				flash.document = result.document
			} else {
				flash.message = "Se produjo un error: el documento no pudo guardarse"
			}
		} catch (RuntimeException e) {
			flash.sucess = false
			flash.message = e.toString()
			log.fatal("Error guardando el documento", e)
		}
		redirect(controller: 'document', action: 'showSaved')
		
	}
	
}
